package com.itheima.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendMovementTask {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/30 * * * * ?")
    public void saveRecommendMovement(){
        System.out.println("推荐动态开始了~~~");
        //1.从redis中获取所有的以”MOVEMENTS_RECOMMEND_”的key,返回集合
        Set<String> keys = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");

        //2.遍历集合获取到每个键值对
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //2.0 获取推荐用户id(key中获取)
                String userId = key.replace("MOVEMENTS_RECOMMEND_", "");
                System.out.println("当前给此用户生成推荐:"+userId);
                //2.1 为了避免重复推荐,先删除mongo中给此用户的所有推荐
                mongoTemplate.remove(new Query(Criteria.where("userId").is(Long.valueOf(userId))), RecommendMovement.class);
                
                //2.2 获取推荐给用户的所有动态,以”,”隔开的字符串的pid
                String pidStr = stringRedisTemplate.opsForValue().get(key);
                
                //2.3 切割字符串生成pid的数组,获取到每个动态的pid
                String[] pidArr = pidStr.split(",");
                for (String pid : pidArr) {
                    //2.4 通过pid获取动态的详情.主要是获取动态id
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.valueOf(pid))), Movement.class);

                    //2.5 封装推荐动态对象,放入mongo中
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());//推荐时间
                    recommendMovement.setUserId(Long.valueOf(userId));//推荐用户id
                    recommendMovement.setPid(Long.valueOf(pid));//动态的pid(大数据id)
                    recommendMovement.setPublishId(movement.getId());//动态id
                    recommendMovement.setScore(RandomUtil.randomDouble(70,99));

                    mongoTemplate.save(recommendMovement);
                }
            }
        }

        System.out.println("推荐动态完成~~~");

    }

}
